package com.ruoyi.oa.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.oa.enums.JinZhiApiEnum;
import com.ruoyi.oa.invoker.JinZhiOpenApiInvoker;
import com.ruoyi.oa.invoker.pojo.dto.JinZhiCallRequest;
import com.ruoyi.oa.invoker.pojo.vo.JinZhiResponseVO;
import com.ruoyi.oa.vo.OaStaffVO;
import com.ruoyi.system.domain.SysUserRole;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.mapper.SysUserRoleMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class SyncOaStaffDataService {

    @Resource
    private JinZhiOpenApiInvoker jinZhiOpenApiInvoker;

    @Resource
    private SysUserMapper sysUserMapper;

    @Resource
    private SysUserRoleMapper sysUserRoleMapper;

    /**
     * 同步用户数据
     */
    @Transactional(rollbackFor = Exception.class)
    public void syncStaff(){
        // 查询现有用户
        SysUser user = new SysUser();
        List<SysUser> sysUserList = sysUserMapper.selectUserList(user);

        // 获取oa中的员工数据
        List<OaStaffVO> oaStaffVOList = this.getOaStaffList();
        if(CollUtil.isEmpty(oaStaffVOList)){
            log.info("oaStaffVO is empty");
            return;
        }

        // 更新或者新增员工信息(若原有数据中有ID则为更新，否则为新增)
        List<SysUser> updateList = new ArrayList<>();
        List<SysUser> insertList = new ArrayList<>();
        for (OaStaffVO oaStaffVO : oaStaffVOList) {
            // 类型转换 oa员工数据-》sysUser数据
            SysUser oaSysUser = new SysUser();
            oaSysUser.setUserName(oaStaffVO.getJzgh());
            oaSysUser.setNickName(oaStaffVO.getXm());
            oaSysUser.setSex("1".equals(oaStaffVO.getXb()) ? "0" : "1");
            oaSysUser.setDeptId(oaStaffVO.getDwh());
            oaSysUser.setPhonenumber(oaStaffVO.getSjhm());
            oaSysUser.setbirthDate(oaStaffVO.getCsrq());
            oaSysUser.setIdNumber(oaStaffVO.getSfzjh());
            // 判断是新增or更新
            Boolean exists = false;
            if(CollUtil.isNotEmpty(sysUserList)){
                exists = sysUserList.stream()
                        .anyMatch(existingUser -> existingUser.getUserName().equals(oaSysUser.getUserName()));
            }
            if (exists) {
                // 更新信息
                updateList.add(oaSysUser);
            }else if(ObjectUtil.isNotEmpty(oaStaffVO.getSfzjh())){
                log.info("staffInfo:{}", JSONUtil.toJsonStr(oaStaffVO));
                // 新增信息，新增时，其密码默认为工号+身份证后6位
                String password = oaStaffVO.getJzgh()+oaStaffVO.getSfzjh().substring(oaStaffVO.getSfzjh().length()-6);
                oaSysUser.setPassword(SecurityUtils.encryptPassword(password));
                // 状态默认正常
                oaSysUser.setStatus(UserConstants.NORMAL);
                insertList.add(oaSysUser);
            }
        }

        // 更新信息
        if(CollUtil.isNotEmpty(updateList)){
            int updateRet = sysUserMapper.updateUserBatch(updateList);
            log.info("update User list success,updateRet:{}", updateRet);
        }
        // 新增信息
        if(CollUtil.isNotEmpty(insertList)){
            int insertRet = sysUserMapper.insertUserBatch(insertList);
            log.info("insert User list success,insertRet:{}", insertRet);

            // 新增用户与角色管理--角色默认为普通角色(角色ID暂时写死)
            List<SysUserRole> userRoleList = new ArrayList<SysUserRole>();
            for (SysUser sysUser : insertList)
            {
                SysUserRole ur = new SysUserRole();
                ur.setUserId(sysUser.getUserId());
                ur.setRoleId(UserConstants.NORMAL_ROLE_ID);
                userRoleList.add(ur);
            }
            sysUserRoleMapper.batchUserRole(userRoleList);
        }
        return;
    }

    /**
     * 获取oa的部门数据
     */
    private List<OaStaffVO> getOaStaffList(){
        // http请求获取oa的机构数据
        JinZhiCallRequest jinZhiCallRequest = new JinZhiCallRequest();
        jinZhiCallRequest.setJinZhiApiEnum(JinZhiApiEnum.SCHOOL_STAFF);
        JinZhiResponseVO jinZhiResponseVO = jinZhiOpenApiInvoker.invoke(jinZhiCallRequest);

        // 获取到的数据
        List<OaStaffVO> oaStaffVOList = new ArrayList<>();
        Object staffListData = jinZhiResponseVO.getValue();
        // 使用 Jackson 进行转换
        try {
            // 创建 ObjectMapper 实例
            ObjectMapper objectMapper = new ObjectMapper();
            // 使用 TypeReference 指定要转换的目标类型
            TypeReference<List<OaStaffVO>> typeReference = new TypeReference<List<OaStaffVO>>() {};;
            // 将 Object 转换为 List
            oaStaffVOList = objectMapper.readValue(JSONUtil.toJsonStr(staffListData), typeReference);
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new RuntimeException(e);
        }
       return oaStaffVOList;
    }


}
